<template>
	<view class="font-mono">
		<view class="search">
			<uni-search-bar v-model="searchValue" bgColor="#EEEEEE" radius="5" :placeholder="$t('flow.process')"
				clearButton="auto" cancelButton="none"></uni-search-bar>
		</view>
		<uni-notice-bar style="margin-bottom: 8rpx;" show-icon show-close scrollable
			:text="$t('flow.bienvenidoIBPM')" />
		<view class="process-count ">
			<view class="count-item todo-item shadow-md" @click="to(0)">
				<view class="item-text">
					<view class=" font-black">{{ $t('flow.disposal') }}</view>
					<view class="text-center">{{ counter.todo }}</view>
				</view>
				<image mode="aspectFit" src="/static/image/pending.png"></image>
			</view>
			<view>
				<view class="count-item shadow-md" @click="to(2)">
					<view class="item-text">
						<view class=" font-black">{{ $t('flow.initiated') }}</view>
						<view>{{ counter.mySubmited }}</view>
					</view>
					<image mode="aspectFit" src="/static/image/submit.png"></image>
				</view>
				<view class="count-item shadow-md" style="margin-top: 5px;" @click="to(3)">
					<view class="item-text">
						<view class=" font-black">{{ $t('flow.copyMe') }}</view>
						<view>{{ counter.cc }}</view>
					</view>
					<image mode="aspectFit" src="/static/image/cc.png"></image>
				</view>
			</view>
		</view>
		<view class="w-app-items">
			<uni-collapse>
				<uni-collapse-item class="w-group shadow-md" :open="true" v-for="(group, index) in dataList"
					:key="'group_' + index + group.items.length" :border="false" title-border="none">
					<template #title>
						<view class="flex flex-row items-center">
							<text class="ml-3 font-black font text-lg">{{ group.name }}</text>
							<!-- <text>({{group.items.length}})</text> -->
							<text
								class="h-4 bg-gradient-to-r from-cyan-500 to-blue-500 text-white mx-1 px-2 rounded-full ">{{group.items.length }}</text>
						</view>

					</template>
					<view class="w-form-items">
						<view class="w-form-item " v-for="(item, i) in group.items" :key="'item_' + index"
							@click="copyOnFileClick(item)">
							<view class="w-form-icon shadow-lg shadow-slate-300"
								:style="'background-color: ' + item.logo.background">
								<l-icon class="w-form-icon-ico" color="#FFFFFF" size="64rpx" :name="item.logo.icon" />
							</view>
							<!-- 放入提示文字 -->
							<uni-tooltip :content="item.formName" placement="top">
								<view class="w-form-name">{{ item.formName }} </view>
							</uni-tooltip>
						</view>
						<!-- 用来占位的 -->
						<view class="w-form-item" style="height: 0;" v-for="(item, i) in 2" :key="'item_' + index">
						</view>
					</view>
				</uni-collapse-item>
			</uni-collapse>
		</view>
		<uni-popup ref="alertDialog" type="dialog">
			<view class="input-dialog-box">
				<view class="input-dialog-content">
					<!-- 标题 -->
					<view class="title">
						<image class="title-img" src="../../static/flieName.png"></image>
						<text>{{$t('homePage.pleaseDraft')}}</text>
					</view>
					<!-- 头部 -->
					<view class="file-name" style="background-color: #dbdcdf;">
						<view class="serial">#</view>
						<view class="name">{{$t('homePage.CopyNoTime')}}</view>
						<view class="controls">{{$t('webAuto.operate')}}</view>
					</view>
					<!-- 存稿内容 -->
					<view :class="data.index == index ? 'file-name2 file-name' : 'file-name'"
						v-for="(item, index) in data.tableData" :key="index" style="font-weight: 400;">
						<view class="serial">{{ index + 1 }}</view>
						<view class="name" @click="selectForm(item, index)">{{ item.name }}</view>
						<button class="mini-btn" type="warn" size="mini" @click="handleClick(item)" style="margin-bottom:5rpx ">{{$t('webAuto.delete')}}</button>
					</view>
				</view>
				<view class="input-dialog-footer">
					<view class="input-dialog-button" @click="cancelFn">
						{{$t('webAuto.cancel')}}
					</view>
					<view class="input-dialog-button dialog-button-left" style="background-color: #D64445;color:#fff"
						@click="confirmFn">
						{{$t('webAuto.DonotManuscripts')}}
					</view>
				</view>
			</view>
		</uni-popup>
	</view>

</template>

<script setup>
import { computed, onMounted, ref, watch, reactive } from 'vue';
import { getGroupModelsByUser, getProcessCountData } from '@/api/model.js'

import { getFormDataStaging, deleteFormDataStaging } from '@/api/process.js'
import { onShow, onPullDownRefresh } from "@dcloudio/uni-app";
import { debounce } from '@/utils/tool.js'
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const searchValue = ref(null)
const searchResult = ref([])
const appList = ref([])
const recentlyUsed = ref([])
const counter = ref({
	cc: 0,
	mySubmited: 0,
	todo: 0
})

let alertDialog = ref(null)
const data = reactive({
	tableList: {},
	tableData: [],
	selectForm: {},
	formDatas:{},
	index: null,// 当前选择的存稿
});

onShow(() => {
	getPageData()
})

onMounted(() => {
	getPageData()
	recentlyUsed.value = uni.getStorageSync('recentlyUsed') || []
})

onPullDownRefresh(() => {
	getPageData()
})

const searchDebounce = debounce(() => doSearch(), 800)

async function filterRecentlyUsed(collect) {
	recentlyUsed.value = recentlyUsed.value.filter(v => collect.has(v.formId))
	recentlyUsedStore()
}

const dataList = computed(() => {
	if ((searchValue.value || '').trim() === '') {
		if (recentlyUsed.value.length > 0) {
			return [{
				id: 0,
				name: t('webAuto.Recentlyused'),
				items: recentlyUsed.value
			}, ...appList.value]
		}
		return appList.value
	}
	return [{
		id: 0,
		name: t('webAuto.SearchResult'),
		items: searchResult.value
	}]
})

function doSearch() {
	searchResult.value.length = 0
	appList.value.forEach(group => {
		group.items.forEach(item => {
			if (item.formName.indexOf(searchValue.value) > -1) {
				searchResult.value.push(item)
			}
		})
	})
}

function getPageData() {
	const idSet = new Set()
	getGroupModelsByUser().then(rsp => {
		appList.value = rsp.data
			.filter(v => v.items.length > 0 && v.id !== 0)
			.map(group => {
				group.items.forEach(item => {
					idSet.add(item.formId)
					item.logo = JSON.parse(item.logo || '{}')
				})
				return group
			})
		filterRecentlyUsed(idSet)
		uni.stopPullDownRefresh()
	}).catch(err => {
		recentlyUsed.value.length = 0
		uni.stopPullDownRefresh()
		uni.showToast({
			title: t('webAuto.FailedApplication'),
			icon: 'fail'
		})
	})

	getProcessCountData().then(rsp => {
		counter.value = rsp.data
		uni.stopPullDownRefresh()
	}).catch(err => {
		uni.stopPullDownRefresh()
		uni.showToast({
			title: t('webAuto.FailedInformation'),
			icon: 'fail'
		})
	})
}

function to(v) {
	uni.switchTab({
		url: '/pages/workspace/workspace'
	})
	setTimeout(() => {
		uni.$emit('to:workspace', v)
	}, 200)
}

// 发起流程点击的方法
function toSubmit(item) {
	if (!item.processDefId) {
		uni.showToast({
			icon: 'none',
			title: t('webAuto.ProcessReleased')
		})
		return
	}
	const i = recentlyUsed.value.findIndex(v => item.formId === v.formId)
	if (i > -1) {
		recentlyUsed.value.splice(i, 1)
	}
	if (recentlyUsed.value.length > 10) {
		recentlyUsed.value.splice(recentlyUsed.value.length - 1, 1)
	}
	recentlyUsed.value.unshift(item)
	recentlyUsedStore()
	uni.navigateTo({
		url: `/pages/submit/InitiateProcess?code=${item.formId}`
	})
}

// 是否有存稿的数据
function copyOnFileClick(item) {
	alertDialog.value.open();
	data.index=null
	data.selectForm = item
	data.tableData = []
	getFormDataStaging(item.formId).then(res => {
		Object.keys(res.data).forEach(item => {
			data.tableData.push({
				name: item
			})
		})
		data.tableList = res.data
		if (!data.tableData.length) {
			alertDialog.value.close();
			// this.openItemDl2 = false
			toSubmit(data.selectForm)
		}
	})
}

// 不使用存稿打开流程
const confirmFn = () => {
	alertDialog.value.close();
	toSubmit(data.selectForm)
}

// 取消按钮
const cancelFn = () => {
	alertDialog.value.close();
	data.index = null
}

// 使用存稿的时候
const selectForm = (item, index) => {
	data.index = index
	data.formDatas=data.tableList[item.name]
	// console.log(data.formDatas)
	uni.navigateTo({
		url: `/pages/submit/InitiateProcess?code=${data.selectForm.formId}&formDatas=${JSON.stringify(data.formDatas)}`
	})
	alertDialog.value.close();
}

// 删除存稿
const handleClick = (item) => {
	// console.log(data.selectForm.processDefId)
	deleteFormDataStaging({
		stagingDate: item.name,
		formId: data.selectForm.formId
	}).then(res => {
		uni.showToast({
			icon: 'none',
			title: res.data
		})
		let subscript = ''
		data.tableData.filter(function (value, index, arr) {
			if (value.name == item.name) {
				subscript = index
			}
		});
		data.tableData.splice(subscript, 1)
		if(data.tableData.length==0){
			alertDialog.value.close();
			toSubmit(data.selectForm)
		}
	}).catch(err => {
		uni.showToast({
			icon: 'none',
			title: t('webAuto.DeleteFailed') + err.data
		})
	})
}

function recentlyUsedStore() {
	uni.setStorageSync('recentlyUsed', recentlyUsed.value)
}

watch(searchValue, async () => {
	searchDebounce()
})
</script>

<style lang="less" scoped>
/* 加载自定义样式 */
@import "../../css/index.css";

page {
	background-color: #F4F5F7;
}

.w-group {
	padding: 38rpx 0 18rpx 0;
	width: auto;
	background-color: white;
	margin: 6rpx 0;
	border-radius: 10rpx;
}

.w-group-title {
	font-weight: 600;
	font-size: 35rpx;
	// font-size: 20rpx;
	margin-left: 32rpx;
}

.search {
	background-color: white;
}

.w-app-items {
	padding: 0rpx 16rpx;

	:deep(.uni-collapse) {
		background: none;
	}
}

.process-count {
	display: flex;
	padding: 0rpx 4rpx;

	&>view:first-child {
		width: 40%;
	}

	&>view:last-child {
		width: 60%;

	}

	.todo-item {
		image {
			width: 96rpx;
			height: 96rpx;
		}

		.item-text {
			display: block;
			height: 100%;

			&>view:first-child {
				margin-bottom: 38rpx;
			}

			&>view:last-child {
				color: #EC8151 !important;
				font-weight: bold;
				font-size: 58rpx !important;
			}
		}
	}

	.count-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 6rpx;
		background-color: #FFFFFF;
		border-radius: 10rpx;
		padding: 16rpx;

		.item-text {
			&>view:last-child {
				color: #B9B8B8;
				font-weight: bold;
				font-size: 38rpx;
			}
		}
	}

	image {
		width: 58rpx;
		height: 58rpx;
	}


}

.w-form-items {
	display: flex;
	flex-wrap: wrap;
	padding: 32rpx;
	justify-content: space-between;

	.w-form-item {
		margin-top: 15rpx;
		width: 144rpx;
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: center;
	}

	.w-form-name {
		width: 128rpx;
		padding: 6rpx 0;
		overflow: hidden;
		text-align: center;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.w-form-icon {
		width: 96rpx;
		height: 96rpx;
		border-radius: 26rpx;
		background-color: burlywood;
		display: flex;
		justify-content: center;
		align-items: center;

		.w-form-icon-ico {
			color: white;
		}
	}
}

// 弹框存稿
.title {
	font-size: 32rpx;
	width: 100%;
	text-align: left;
	color: #0c741c;
	font-weight: 600;
	display: flex;
	flex-direction: row;
	position: relative;
	padding-left: 8rpx;

	.title-img {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}
}

.title::after {
	content: '';
	position: absolute;
	left: -6rpx;
	top: 4rpx;
	width: 6rpx;
	height: 35rpx;
	background-color: #0c741c;
}

.file-name {
	margin: 20rpx 0;
	width: 100%;
	display: flex;
	flex-direction: row;
	font-size: 28rpx;
	font-weight: 600;
	line-height: 60rpx;
	border-bottom: 2rpx solid #E5E5E5;

	.serial {
		width: 15%;
	}

	.name {
		flex: 1;
	}

	.controls {
		width: 20%;
	}
}

.file-name2 {
	background-color: #EBB577;
}
</style>